<?php

function C($name = null, $value = null, $append = false)
{
    if ($name === null)
        return \core\kyo::$config;

    if (is_array($name)) {
        \core\kyo::$config = $name + \core\kyo::$config;
    } else if ($value !== null) {
        if (!$append) {
            \core\kyo::$config[$name] = $value;
        } else if (is_array(\core\kyo::$config[$name])) {
            array_push(\core\kyo::$config[$name], $value);
        } else {
            \core\kyo::$config[$name] += $value;
        }

    } else {
        return \core\kyo::$config[$name];
    }
}

function U($path = "", $arg = [])
{
    if ($path != "" && $path != ".")
        $url = explode("/", $path);
    else
        $url = [];
    $method = array_pop($url) ?? C('ACTION_NAME');
    $ctl = array_pop($url) ?? C('CONTROLLER_NAME');
    $mod = array_pop($url) ?? C('MODULE_NAME');
    $url = $_SERVER['SCRIPT_NAME'].DS.$mod.DS.$ctl.DS.$method;
    foreach ($arg as $val) {
        $url .= '/'.$val;
    }

    return $url;
}

function R($path, $arg = [])
{
    $save_method = C('ACTION_NAME');
    $save_ctl = C('CONTROLLER_NAME');
    $save_mod = C('MODULE_NAME');
    $name = explode('/', $path);
    if (count($name) < 2)
        E('参数有误，无法执行远程调用!');

    $method = array_pop($name);
    $ctl = array_pop($name);
    if ($ctl == $save_ctl)
        E('本控制器的方法就没有这样调用!');
    $mod = array_pop($name) ?? $save_mod;

    C('MODULE_NAME', $mod);
    C('CONTROLLER_NAME', $ctl);
    C('ACTION_NAME', $method);

    $classname = '\\'.$mod.'\\'.$ctl;
    $obj = new $classname;

    $data = call_user_func_array(array($obj, $method), $arg);

    C('MODULE_NAME', $save_mod);
    C('CONTROLLER_NAME', $save_ctl);
    C('ACTION_NAME', $save_method);

    return $data;
}

function M($table = null)
{
    $model = \core\Model::getInstance($table);
    return $model;
}

function E($mes, $code = 0)
{
    throw new \Exception($mes, $code);
}

function dump_array($array)
{
    static $level = 0;

    $indent = "";

    for ($i = 0; $i < $level; ++$i) {
        $indent .= '&emsp;&emsp;';
    }

    $level++;

    $str = $indent.'array (<br />';
    foreach ($array as $key => $val) {
        if (is_array($val)) {
            $str .= dump_array($val);
            $level--;
        } else {
            $str .= $indent.$indent."'".$key."'&nbsp;=>&nbsp;'".$val."',<br />";
        }
    }
    $str .= $indent.')<br />';

    return $str;
}

function dump($val, $title = null, $return = false)
{
    if (is_array($val))
        $content = dump_array($val);
    else
        $content = $val;

    if ($title === null)
        $title = "";
    else
        $title = '<h1 style="border-bottom:1px #000 solid">'.$title.'</h1>';

    $html = <<< EOF
<div class=".dump" style="border: 1px #f00 solid; font-size:14px;padding:10px;">
    $title
    $content
</div>
EOF;
    if ($return)
        return $html;
    echo $html;
}

function sqlAll($sql)
{
    return M()->query($sql);
}

function sqlRow($sql)
{
    return M()->query($sql, \core\Model::ROW);
}

function sqlCol($sql)
{
    return M()->query($sql, \core\Model::COL);
}


function json_return($msg, $url = null, $tag = null, $close = null, $callback = null)
{
    if (is_array($msg)) {
        $json = $msg;
    } else {
        $json['msg'] = $msg;
        $url !== null && $json['url'] = $url;
        $tag !== null && $json['tag'] = $tag;
        $close !== null && $json['close'] = $close;
        $callback !== null && $json['callback'] = $callback;
    }

    return json_encode($json);
}

function json_return_data($data, $type = 'html', $tag = null)
{
    return json_encode([
            'type' => $type,
            'tag' => $tag,
            'data' => $data
        ]);
}

function sql_log($sql, $title)
{
    $logpath = '/dev/shm/sql.log';
    $log = '';
    if (file_exists($logpath)) {
        $log = file_get_contents('/dev/shm/sql.log');
    }
    $log .= '['.date("Y-m-d H:i:s").'] '.$title.PHP_EOL."\t".$sql.PHP_EOL;
    file_put_contents('/dev/shm/sql.log', $log);
    // exit(0);
}

function getRedis()
{
    static $redis = null;

    if ($redis == null) {
        $redis = new Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->auth('redis');
    }

    return $redis;
}

function redis_set($name, $val)
{
    $redis = getRedis();
    $redis->set($name, $val);
}

function redis_has($key)
{
    $redis = getRedis();
    return $redis->exists($key);
}

function redis_get($name)
{
    $redis = getRedis();
    return $redis->get($name);
}

function session($name = null, $value = null, $append = false)
{
    if ($name === null)
        return $_SESSION;

    if (is_array($name)) {
        $_SESSION = $name + $_SESSION;
    } else if ($value !== null) {
        if (!$append) {
            $_SESSION[$name] = $value;
        } else if (is_array($_SESSION[$name])) {
            array_push($_SESSION[$name], $value);
        } else {
            $_SESSION[$name] += $value;
        }

    } else {
        return $_SESSION[$name] ?? false;
    }
}

function check_login()
{
    if (!session('auth')) {
        if (IS_AJAX)
            exit(json_return('登录超时!', U('admin/Index/login')));
        header('location:'.U('admin/Index/login'));
    }
}

function page_fetch($total, $url, $nowPage = null, $tag = "#datalist", $size = null)
{
    if ($total == 0)
        return ['limit' => '', 'html' => ''];

    $key = 'kyoPage'.$tag;
    if ($nowPage == null) {
        if (session($key))
            $nowPage = session($key);
        else {
            $nowPage = 1;
            session($key, 1);
        }
    } else {
        session($key, $nowPage);
    }

    //获取一页多少条记录
    $pageSize = $size ?? C('PAGE_SIZE');
    //获取总共显示多少页
    $pageRoll = C('PAGE_ROLL');
    //获取总页数
    $totalPage = ceil($total / $pageSize);

    //获取页栏中间页
    $rollMid = floor($pageRoll / 2);
    $rollMidCeil = ceil($rollMid);

    $nowPage < 1 && $nowPage = 1;
    $nowPage > $totalPage && $nowPage = $totalPage;
    //计算数据库起始位置
    $pageStart = ($nowPage - 1) * $pageSize;
    $pageReturn['limit'] = ' LIMIT '.$pageStart.','.$pageSize;

    $href = 'javascript:void(0)';
    $ls = 'kyo-link=\'"url":"'.$url.'/';
    $le = '", "tag":"'.$tag.'", "ajax": true\'';

    //上一页
    $up_page = "";
    $up_row = $nowPage - 1;
    if ($up_row > 0 && $totalPage > $pageRoll) {
        $up_page = '<li class="page-prev"><a href="'.$href.'" ';
        $up_page .= $ls.$up_row.$le;
        $up_page .= '>上一页</a></li>';
    }

    //下一页
    $down_page = "";
    $down_row = $nowPage + 1;
    if ($down_row < $totalPage && $totalPage > $pageRoll) {
        $down_page = '<li class="page-next"><a href="'.$href.'" ';
        $down_page .= $ls.$down_row.$le;
        $down_page .= '>下一页</a></li>';
    }

    //首页
    $first_page = "";
    if ($nowPage > $rollMid + 1) {
        $first_page = '<li class="page-first"><a href="'.$href.'" ';
        $first_page .= $ls.'1'.$le;
        $first_page .= '>1</a></li>';
    }

    //尾页
    $last_page = "";
    if ($totalPage > $pageRoll && $nowPage + $rollMid < $totalPage) {
        $last_page = '<li class="page-last"><a href="'.$href.'" ';
        $last_page .= $ls.$totalPage.$le;
        $last_page .= '>'.$totalPage.'</a></li>';
    }

    //显示数字链接页

    $link_page = "";
    if ($totalPage > 1) {
        if ($nowPage <= $rollMid)
            $start = 1;
        else if ($totalPage > $pageRoll && $nowPage + $rollMid > $totalPage)
            $start = $totalPage - $pageRoll + 1;
        else
            $start = $nowPage - $rollMid;

        $end = $totalPage < $pageRoll ? $totalPage : $start + $pageRoll - 1;
        for ($i = $start; $i <= $end; ++$i) {
            if ($i == $nowPage)
                $link_page .= '<li class="active"><a href="'.$href.'" ';
            else
                $link_page .= '<li class="page-num"><a href="'.$href.'" ';
            $link_page .= $ls.$i.$le.' >'.$i.'</a></li>';
        }
    }

    $pageReturn['html'] = '<div class="row text-center"><ul class="pagination">';
    $pageReturn['html'] .= $first_page.$up_page.$link_page.$down_page.$last_page;
    $pageReturn['html'] .= '<li><a href="'.$href.'">共&nbsp;';
    $pageReturn['html'] .= '<span class="page-total">'.$total.'</span>';
    $pageReturn['html'] .= '&nbsp;条记录</a></li></ul></div>';

    return $pageReturn;
}

